package com.example.gulimall.search.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.common.constant.SearchConstant;
import com.example.common.exception.RRException;
import com.example.common.to.AttrResponseTo;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.common.config.es.GulimallElasticsearchConfig;
import com.example.gulimall.search.feign.ProductFeignService;
import com.example.gulimall.search.service.MallSearchService;
import com.example.gulimall.search.vo.SearchParam;
import com.example.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    private static final String REGEX_COLON = ":";
    private static final String REGEX_SEMICOLON = ";";
    private static final String REGEX_UNDERLINE = "_";

    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info("商品检索条件: {}", param.toString());
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        SearchRequest request = this.buildSearchRequest(param);

        try {
            SearchResponse search = client.search(request, GulimallElasticsearchConfig.COMMON_OPTIONS);
            SearchResult result = this.buildSearchResult(search, param);

            log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            log.info("商品查询返回结果: {}", result.toString());
            log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

            return result;
        } catch (IOException e) {

            log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            log.error("商品检索错误信息: ", e);
            log.error("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

            throw new RRException(e.getMessage());
        }
    }

    // ****************************************** request methods ~ ***********************************************

    /**
     * 构建查询dsl
     * <p>
     * 模糊匹配,过滤(属性，分类，品牌，价格区间，库存),排序,分页,高亮,聚合分析
     *
     * @return request
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 模糊匹配,过滤(属性，分类，品牌，价格区间，库存)
        this.boolQuery(builder, param);
        // 排序
        this.sort(builder, param);
        // 分页
        this.page(builder, param);
        // 高亮
        this.highlight(builder, param);
        // 聚合分析
        this.aggs(builder);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info("商品检索 dsl: {}", builder.toString());
        log.info("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        return new SearchRequest(new String[]{SearchConstant.PRODUCT_INDEX}, builder);
    }

    /**
     * 聚合操作
     *
     * @param builder 创建查询条件
     */
    private void aggs(SearchSourceBuilder builder) {
        // brand_agg
        this.brandAgg(builder);
        // catalog_agg
        this.catalogAgg(builder);
        // attr_agg
        this.attrAgg(builder);
    }

    /**
     * 嵌入式聚合
     *
     * @param builder 查询结果
     */
    private void attrAgg(SearchSourceBuilder builder) {

        NestedAggregationBuilder nested = AggregationBuilders
                .nested("attr_agg", "attrs")
                .subAggregation(
                        AggregationBuilders.terms("attr_id_agg")
                                .field("attrs.attrId")
                                .size(1)
                                .subAggregation(
                                        AggregationBuilders.terms("attr_name_agg")
                                                .field("attrs.attrName")
                                                .size(1)
                                )
                                .subAggregation(
                                        AggregationBuilders.terms("attr_value_agg")
                                                .field("attrs.attrValue")
                                                .size(50)
                                )
                );

//        TermsAggregationBuilder attrAgg = AggregationBuilders
//                .terms("attr_agg")
//                .field("attrs.attrId")
//                .size(50);
//        attrAgg.subAggregation(
//                AggregationBuilders
//                        .terms("attr_Id_agg")
//                        .field("attrs.attrId")
//                        .size(50)
//        );
//        attrAgg.subAggregation(
//                AggregationBuilders
//                        .terms("attr_value_agg")
//                        .field("attrs.attrValue")
//                        .size(50)
//        );
        builder.aggregation(nested);
    }

    private void catalogAgg(SearchSourceBuilder builder) {
        TermsAggregationBuilder catalogAgg = AggregationBuilders
                .terms("catalog_agg")
                .field("catalogId")
                .size(50);

        catalogAgg.subAggregation(
                AggregationBuilders
                        .terms("catalog_name_agg")
                        .field("catalogName")
                        .size(50)
        );
        builder.aggregation(catalogAgg);
    }

    /**
     * 针对品牌的聚合
     *
     * @param builder 查询条件
     */
    private void brandAgg(SearchSourceBuilder builder) {
        TermsAggregationBuilder brandAgg = AggregationBuilders
                .terms("brand_agg")
                .field("brandId")
                .size(50);

        brandAgg.subAggregation(
                AggregationBuilders.terms("brand_name_agg")
                        .field("brandName")
                        .size(50))
                .subAggregation(
                        AggregationBuilders.terms("brand_image_agg")
                                .field("brandImg")
                                .size(50)
                );
        builder.aggregation(brandAgg);
    }

    private void highlight(SearchSourceBuilder builder, SearchParam param) {
        if (StringUtils.isBlank(param.getKeyword())) {
            return;
        }
        builder.highlighter(
                new HighlightBuilder()
                        .field("skuTitle")
                        .preTags("<b style='color:red'>")
                        .postTags("</b>")
        );
    }

    /**
     * 分页
     *
     * @param builder 查询条件
     * @param param   查询参数
     */
    private void page(SearchSourceBuilder builder, SearchParam param) {
        builder.from((param.getPageNum() - 1) * SearchConstant.PRODUCT_PAGE_SIZE);
        builder.size(SearchConstant.PRODUCT_PAGE_SIZE);
    }

    /**
     * 排序
     *
     * @param builder 查询条件
     * @param param   查询参数
     */
    private void sort(SearchSourceBuilder builder, SearchParam param) {
        /*
         排序条件
         sort=saleCount_desc
         sort=skuPrice_desc
         sort=hotScore_desc
        */
        if (StringUtils.isBlank(param.getSort())) {
            return;
        }

        String[] split = param.getSort().split(REGEX_UNDERLINE);
        builder.sort(split[0], SortOrder.fromString(split[1]));
    }

    private void boolQuery(SearchSourceBuilder builder, SearchParam param) {
        /*
        模糊匹配,过滤(属性，分类，品牌，价格区间，库存)
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 模糊匹配
        if (StringUtils.isNotBlank(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        // 过滤 - 分类
        if (Objects.nonNull(param.getCatalog3Id())) {
            // boolQuery.filter(QueryBuilders.termsQuery("catalogId", param.getCatalog3Id()));
        }

        // 过滤 - 品牌
        if (CollectionUtil.isNotEmpty(param.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        // 过滤 - 属性
        nestedAttrs(boolQuery, param.getAttrs());

        // 过滤 - 库存
        if (Objects.nonNull(param.getHasStock())) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        // 过滤 - 价格区间
        rangeSkuPrice(boolQuery, param.getSkuPrice());

        builder.query(boolQuery);
    }


    /**
     * 价格区间查询
     *
     * @param boolQuery 查询条件
     * @param skuPrice  价格区间
     */
    private void rangeSkuPrice(BoolQueryBuilder boolQuery, String skuPrice) {
        if (StringUtils.isBlank(skuPrice)) {
            return;
        }

        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

        String[] split = skuPrice.split(REGEX_UNDERLINE);
        if (split.length == 2) {
            rangeQuery.gte(split[0]).lte(split[1]);
        }
        if (skuPrice.startsWith(REGEX_UNDERLINE)) {
            rangeQuery.lte(split[1]);
        }
        if (skuPrice.endsWith(REGEX_UNDERLINE)) {
            rangeQuery.lte(split[0]);
        }

        boolQuery.filter(rangeQuery);
    }

    /**
     * 嵌套查询，es 7.12.3 版本好像嵌套失败了
     *
     * @param boolQuery bool 查询条件构造
     * @param attrs     所有的属性
     */
    private void nestedAttrs(BoolQueryBuilder boolQuery, List<String> attrs) {
        if (CollectionUtil.isEmpty(attrs)) {
            return;
        }
        /* 弃用 nested  */
        for (String attrStr : attrs) {

            if (StringUtils.isBlank(attrStr)
                    || !attrStr.contains(REGEX_UNDERLINE)
                    || !attrStr.contains(REGEX_COLON)) {
                continue;
            }

            BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
            //  attrs=1_安卓:IOS&attrs=2_3G:4G

            String[] s = attrStr.split(REGEX_UNDERLINE);
            String attrId = s[0];
            String[] attrValues = s[1].split(REGEX_COLON);

            nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
            nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));

            // nested
            NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
            boolQuery.filter(nestedQuery);
        }
//        for (String attrStr : attrs) {
//
//            if (StringUtils.isBlank(attrStr)
//                    || !attrStr.contains(REGEX_UNDERLINE)
//                    || !attrStr.contains(REGEX_COLON)) {
//                continue;
//            }
//
//            //  attrs=1_安卓:IOS&attrs=2_3G:4G
//            String[] s = attrStr.split(REGEX_UNDERLINE);
//            String attrId = s[0];
//            String[] attrValues = s[1].split(REGEX_COLON);
//
//
//            boolQuery.filter(QueryBuilders.termQuery("attrs.attrId", attrId))
//                    .filter(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
//        }
    }

    // ****************************************** response methods ~ ***********************************************

    /**
     * 构建出返回结果
     *
     * @param search 查询返回结果
     * @param param  分页参数
     * @return 自定义结果
     */
    private SearchResult buildSearchResult(SearchResponse search, SearchParam param) {
        SearchResult result = new SearchResult()
                .setPageNum(param.getPageNum());
        /*

        hits:{},
        aggregations:{}

         */
        SearchHits hits = search.getHits();
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 计算总页码
        int intTotal = (int) total;
        int size = intTotal / SearchConstant.PRODUCT_PAGE_SIZE;
        int totalPage = intTotal % SearchConstant.PRODUCT_PAGE_SIZE == 0 ? size : size + 1;
        result.setTotalPage(totalPage);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i < totalPage; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 遍历封装商品
        this.setProduct(result, hits, param.getKeyword());
        // 封装聚合条件
        this.setAgg(search, result);
        // 封装面包屑导航
        this.setNav(result, param);
        return result;
    }

    private void setNav(SearchResult result, SearchParam param) {

        // 6. 构建面包屑导航
        List<String> attrs = param.getAttrs();
        if (CollectionUtil.isNotEmpty(attrs)) {
            List<SearchResult.NavVo> navVos = attrs.stream().map(attr -> {
                String[] split = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //6.1 设置属性值
                navVo.setNavValue(split[1]);
                //6.2 查询并设置属性名
                try {
                    R r = productFeignService.attrInfo(Long.parseLong(split[0]));
                    if (r.getCode() == 0) {
                        AttrResponseTo to = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrResponseTo>() {
                        });
                        navVo.setNavName(to.getAttrName());
                    } else {
                        navVo.setNavName(split[0]);
                    }
                } catch (Exception e) {
                    log.error("远程调用商品服务查询属性失败", e);
                }
                //6.3 设置面包屑跳转链接(当点击该链接时剔除点击属性)
                String queryString = param.get_queryString();
                String replace = queryString.replace("&attrs=" + attr, "").replace("attrs=" + attr + "&", "").replace("attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html" + (replace.isEmpty() ? "" : "?" + replace));
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVos);
        }
    }

    /**
     * 封装聚合条件
     *
     * @param search 查询结果
     * @param result 返回前端结果
     */
    private void setAgg(SearchResponse search, SearchResult result) {
        // 设置分类信息到聚合结果
        this.setCatalogAgg(search, result);
        // 设置品牌信息
        this.setBrandAgg(search, result);
        // 设置属性结果
        this.setAttrAgg(search, result);
    }

    /**
     * 封装属性结果
     *
     * @param search 查询结果
     * @param result 返回前端结果
     */
    private void setAttrAgg(SearchResponse search, SearchResult result) {
        ParsedNested attrAgg = search.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> buckets = attrIdAgg.getBuckets();

        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {

            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            List<? extends Terms.Bucket> attrNameBucket = attrNameAgg.getBuckets();

            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<? extends Terms.Bucket> attrValueBuckets = attrValueAgg.getBuckets();
            // 解析属性值
            List<String> collect = attrValueBuckets.stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());

            attrVos.add(
                    new SearchResult.AttrVo()
                            .setAttrId(bucket.getKeyAsNumber().longValue())
                            .setAttrName(attrNameBucket.size() > 0 ? attrNameBucket.get(0).getKeyAsString() : "")
                            .setAttrValue(collect)

            );
        }
        result.setAttrs(attrVos);
    }

    /**
     * 设置品牌信息
     *
     * @param search 查询响应结果
     * @param result 封装的结果
     */
    private void setBrandAgg(SearchResponse search, SearchResult result) {
        ParsedLongTerms brandAgg = search.getAggregations().get("brand_agg");

        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {

            ParsedStringTerms brandImageAgg = bucket.getAggregations().get("brand_image_agg");
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");

            List<? extends Terms.Bucket> brandImageBuckets = brandImageAgg.getBuckets();
            List<? extends Terms.Bucket> brandNameBuckets = brandNameAgg.getBuckets();
            brandVos.add(
                    new SearchResult.BrandVo()
                            .setBrandId(bucket.getKeyAsNumber().longValue())
                            .setBrandImg(brandImageBuckets.size() > 0 ? brandImageBuckets.get(0).getKeyAsString() : "")
                            .setBrandName(brandNameBuckets.size() > 0 ? brandNameBuckets.get(0).getKeyAsString() : "")
            );
        }

        result.setBrands(brandVos);
    }

    /**
     * 设置分类信息
     *
     * @param search 查询响应的结果
     * @param result 封装自己的结果
     */
    private void setCatalogAgg(SearchResponse search, SearchResult result) {
        ParsedLongTerms catalogAgg = search.getAggregations().get("catalog_agg");

        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();

        List<? extends Terms.Bucket> buckets = catalogAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {

            Aggregations aggregations = bucket.getAggregations();
            ParsedStringTerms catalogNameAgg = aggregations.get("catalog_name_agg");

            List<? extends Terms.Bucket> aggBuckets = catalogNameAgg.getBuckets();
            catalogVos.add(
                    new SearchResult.CatalogVo()
                            .setCatalogId(bucket.getKeyAsNumber().longValue())
                            .setCatalogName(aggBuckets.size() > 0 ? aggBuckets.get(0).getKeyAsString() : "")
            );
        }
        result.setCatalogs(catalogVos);
    }


    /**
     * 设置高亮
     *
     * @param result  返回前端结果
     * @param hits    命中结果
     * @param keyword 关键字检索
     */
    private void setProduct(SearchResult result, SearchHits hits, String keyword) {
        List<SkuEsModel> esModels = new ArrayList<>();
        for (SearchHit hit : hits) {
            SkuEsModel skuEsModel = JSONObject.parseObject(hit.getSourceAsString(), SkuEsModel.class);
            //设置高亮属性
            if (StringUtils.isNotBlank(keyword)) {
                skuEsModel.setSkuTitle(
                        hit.getHighlightFields()
                                .get("skuTitle")
                                .getFragments()[0]
                                .string());
            }
            esModels.add(skuEsModel);
        }
        result.setProducts(esModels);
    }


}
